package socket;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class SeverDemo {

	public static void main(String[] args) {
		try {
			ServerSocket server=new ServerSocket(8899);//建立名为server的服务器，端口为8899
			System.out.println("服务器启动");  //输出”服务器启动“
			System.out.println(server.getLocalPort()); //输出
			Socket socket=server.accept();
			System.out.println(socket.getPort());
			System.out.println("客户端连接");
			ObjectInputStream in=new ObjectInputStream(socket.getInputStream());
			ObjectOutputStream out=new ObjectOutputStream(socket.getOutputStream());
			Scanner kbin=new Scanner(System.in);
			String m;		
			String send;
			do{
				m=(String)in.readObject();//从网络接受客户端信息
				System.out.println("客户端说："+m);
				send=kbin.nextLine();
				out.writeObject(send);
				out.flush();
			}while(!m.equals("bye"));
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("在同一台电脑上，只能运行一个实例");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

//	@Override
//	public void run() {
//		try {
//			Socket socket=new Socket("192.168.1.101", 8899);
//			Scanner in=new Scanner(System.in);
//			String message;
//			ObjectOutputStream out=new ObjectOutputStream(socket.getOutputStream());
//			do{
//				message=in.nextLine();
//				out.writeObject(message);
//				out.flush();
//			}while(!message.equals("bye"));
//			in.close();socket.close();
//		} catch (UnknownHostException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
}
